# -*- coding: utf-8 -*-
from twisted.internet import threads, reactor, defer
from twisted.web.client import getPage
from threading import Thread
from twisted.web.error import Error
import gobject
import urllib
import simplejson as json

SERVER_IP = "127.0.0.1"
SERVER_PORT = 12345


FEEDBACKSERVER_IP = "127.0.0.1"
FEEDBACKSERVER_PORT = 12345


gobject.threads_init()


def functioninThread():
    print "In function"
    result = {}
    result['id'] = 12
    result['user'] = 'Florian'
    result['content'] = "test"
    result['hihi'] = "hihihi"

    print result
    result = urllib.urlencode(result)
    #result = json.dumps(result)
    
    try:
        #result = threads.blockingCallFromThread(
            #reactor, getPage, "http://%s:%d/survey" % (FEEDBACKSERVER_IP, FEEDBACKSERVER_PORT), headers={"Content-Type":"application/json"}, method="POST", postdata =  result, timeout = 10)

        result = threads.blockingCallFromThread(
            reactor, getPage, "http://%s:%d/survey" % (FEEDBACKSERVER_IP, FEEDBACKSERVER_PORT), headers={'Content-Type':'application/x-www-form-urlencoded '}, method="POST", postdata =  result, timeout = 10)
        
    
    except Error, exc:
        print exc
    else:
        print result
        
    reactor.callFromThread(reactor.stop)
    return False

mainloop = gobject.MainLoop()


gobject.idle_add(functioninThread)


#reactor.connectTCP(SERVER_IP, SERVER_PORT, events_manager.ClientHomeboxFactory(self.events, video))    
twistedThread = Thread( target = reactor.run, kwargs = {'installSignalHandlers':False} )
twistedThread.setDaemon(True)
twistedThread.start()

mainloop.run()